<template>
  <div class="user-avatar">
    <img class="img" :src="img" ref="userAvatar" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'UserAvatar',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data() {
    return {}
  },
  created() {},
  mounted() {
    const image = this.$refs.userAvatar
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    onConfirm() {
      // 基于服务端的裁切使用 getData 方法获取裁切参数
      // console.log(this.cropper.getData())

      // 纯客户端的裁切使用 getCroppedCanvas 获取裁切的文件对象
      // this.cropper.getCroppedCanvas().toBlob(blob => {
      //   console.log(blob)
      //   this.$emit('update-photo', blob)
      // })
      const dataUrl = this.cropper.getCroppedCanvas().toDataURL('image/png')
      this.$emit('update-photo', dataUrl)
    }
  }
}
</script>

<style scoped lang="less">
.user-avatar {
  background-color: #000;
  height: 100%;
  .img {
    display: block;
    max-width: 100%;
  }
  .toolbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    color: #fff;
    display: flex;
    justify-content: space-between;
    padding: 20px 20px 0;
  }
}
</style>
